package com.aote.rs.db;

import com.aote.expression.OccasionConditionFactory;
import com.aote.rs.helper.CharacterSetHelper;
import com.aote.util.ExpressionHelper;
import com.browsesoft.EntityManager;
import com.browsesoft.SequenceFind;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.parameter.Parameter;
import com.browsesoft.user.User;
import java.io.PrintStream;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

@Path("/db")
public class DBServer {
	private static Logger log = Logger.getLogger(DBServer.class);

	@GET
	public String query(@QueryParam("source") String xpath,
			@QueryParam("search") String search,
			@QueryParam("page") String page,
			@QueryParam("pagesize") String pagesize) {
		String result = "";
		String sql = "select * from " + getQuerySQL(xpath, search);
		System.out.println(sql);
		try {
			if ((page != null) && (pagesize != null) && (!page.equals(""))
					&& (!pagesize.equals(""))) {
				int start = Integer.parseInt(page) * Integer.parseInt(pagesize);
				int count = Integer.parseInt(pagesize);
				String table = getQuerySQL(xpath, search);
				sql = getSqlServerLimit(start, count, table);
				String[][] str = DBTools.executeLimitQuery(sql, start, count);
				List list = DBTools.arrayToHashtable(str);
				result = JSONArray.fromObject(list).toString();
			} else {
				String[][] str = DBTools.executeQueryWithTableHead(sql);
				List list = DBTools.arrayToHashtable(str);
				result = JSONArray.fromObject(list).toString();
			}
			System.out.println(result);
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	@Path("/one")
	@GET
	public String oneQuery(@QueryParam("source") String source) {
		String result = "";
		String sql = "select * from " + getQuerySQL(source, null);
		System.out.println(sql);
		try {
			String[][] str = DBTools.executeQueryWithTableHead(sql);
			Hashtable ht = DBTools.getAttributes(str, 1);
			result = JSONObject.fromObject(ht).toString();
		} catch (Exception e) {
			result = "没有找到您要的信息！";
		} finally {
			return result;
		}
	}

	@Path("/rollback")
	@GET
	public String rollback(@QueryParam("userid") String userid,
			@QueryParam("payfeedate") String payfeedate) {
		log.debug("制卡失败:userid=" + userid + ",payfeedate=" + payfeedate);

		String sql = "select * from t_SellingGas where f_userid='" + userid
				+ "' and f_deliverydate='" + payfeedate + "'";
		try {
			String[][] datas = DBTools.executeQueryWithTableHead(sql);

			if (datas.length < 2) {
				return "";
			}
			Hashtable ht = DBTools.getAttributes(datas, 1);

			sql = "update t_SellingGas set f_payfeevalid='无效' where f_userid='"
					+ userid + "' and f_deliverydate='" + payfeedate + "'";
			DBTools.excuteUpdate(sql);
			log.debug("制卡失败rollback执行完成:userid=" + userid + ",payfeedate="
					+ payfeedate);
		} catch (Exception e) {
			log.debug("制卡失败rollback异常:userid=" + userid + ",payfeedate="
					+ payfeedate + "errro:" + e.getMessage());

			log.error(e.getMessage());
		}
		return "";
	}

	@Path("/allexp")
	@POST
	public String allExpression(String send, @Context HttpServletRequest request) {
		throw new UnsupportedOperationException();
	}

	@POST
	public String save(String send, @QueryParam("update") String update) {
		log.debug("更新:update=" + update + ",data="
				+ CharacterSetHelper.restDecode(send));
		String result = "true";
		try {
			Hashtable data = convert(send);

			data.remove("row");
			if ((update == null) || (update.equals(""))) {
				String selfid = SequenceFind.getID() + "";
				data.put("selfid", selfid);
				DBTools.insert(data);
			} else if (update.equals("true")) {
				DBTools.update(data);
			}
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	@Path("/sellsave")
	@POST
	public String sellsave(String send) {
		log.debug("售气专用保存服务,data=" + CharacterSetHelper.restDecode(send));
		String result = "true";
		try {
			Hashtable data = convert(send);
			data.remove("row");
			String selfid = SequenceFind.getID() + "";
			if (validData(data)) {
				data.put("selfid", selfid);
				DBTools.insert(data);
			}
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	private boolean validData(Hashtable data) {
		boolean result = true;

		String userid = data.get("f_userid").toString();
		String f_preamount = data.get("f_preamount").toString();
		String f_deliverydate = data.get("f_deliverydate").toString();
		String sql = "select id from t_sellinggas where f_userid='" + userid
				+ "' and f_preamount='" + f_preamount
				+ "' and f_deliverydate='" + f_deliverydate + "'";
		try {
			String[][] str = DBTools.executeQueryWithTableHead(sql);
			if (str.length > 1)
				result = false;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Path("/modifypassword")
	@POST
	public String modifyPassword(@Context HttpServletRequest request,
			String send) {
		String result = "true";
		try {
			Hashtable data = convert(send);
			User user = getLoginUser(request);
			String oldpwd = (String) data.get("password");
			String newpwd = (String) data.get("newpassword");
			String affirmPass = (String) data.get("affirmpassword");
			user.modifyPassword(oldpwd, newpwd, affirmPass);
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	@SuppressWarnings("finally")
	@Path("/modifypwd")
	@POST
	public String modifyPwd(@Context HttpServletRequest request, String send) {
		String result = "true";
		try {
			JSONObject sendJson = JSONObject.fromObject(send);
			String sendData = sendJson.get("data").toString();
			Hashtable data = this.convert(sendData);
			String ename = data.get("ename") + "";
			User user = (User) EntityManager.getInstance().getUserForLoginName(
					ename);
			String oldpwd = data.get("password") + "";
			String newpwd = data.get("newpassword") + "";
			String affirmPass = data.get("affirmpassword") + "";
			user.modifyPassword(oldpwd, newpwd, affirmPass);
		} catch (Exception e) {
			result = "操作失败" + e.getMessage() + "";
			throw new RuntimeException(e);
		} finally {
			return result;
		}
	}

	@Path("/excuteUpdate")
	@POST
	public String excuteUpdate(String sql) {
		String result = "true";
		try {
			sql = getQuerySQL(sql, null);
			DBTools.excuteUpdate(sql);
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	@Path("/bankPrintUpdate")
	@POST
	public String bankPrintUpdate(String sql) {
		String result = "true";
		try {
			String[] sqls = sql.split(";");
			for (int i = 0; i < sqls.length; i++) {
				sql = getQuerySQL(sqls[i], null);
				DBTools.excuteUpdate(sqls[i]);
			}
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	@Path("/count")
	@GET
	public String getDataCount(@QueryParam("source") String xpath,
			@QueryParam("search") String search) {
		String result = "";
		String sql = "select count(id) from " + getQuerySQL(xpath, search);
		try {
			if (sql.indexOf("order") != -1) {
				sql = sql.split("order")[0];
			}
			String[][] str = DBTools.executeQueryWithTableHead(sql);
			if (str.length > 1)
				result = str[1][0];
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	@Path("/param")
	@GET
	public String getParam(@QueryParam("param") String param) {
		String result = "";
		Parameter parameter = new Parameter(param);
		try {
			List list = parameter.getParamForRest();
			result = JSONArray.fromObject(list).toString();
		} catch (Exception e) {
			result = "参数：" + param + "错误！";
		} finally {
			return result;
		}
	}

	@PUT
	public String update(String send) {
		String result = "true";
		try {
			Hashtable data = convert(send);
			DBTools.update(data);
		} catch (Exception e) {
			result = e.getMessage();
			throw new RuntimeException(e);
		}
		return result;
	}

	@Path("/delete")
	@GET
	public String delete(@QueryParam("tablename") String tableName,
			@QueryParam("id") String id) {
		String result = "true";
		try {
			DBTools.delete(tableName, id);
		} catch (Exception e) {
			result = e.getMessage();
			throw new RuntimeException(e);
		}
		return result;
	}

	@Path("/query")
	@GET
	public String querySql(@QueryParam("sql") String sql) {
		String result = "";
		System.out.println("SQL: " + sql);
		try {
			String[][] str = DBTools.executeQueryWithTableHead(sql);
			List list = DBTools.arrayToHashtable(str);
			result = JSONArray.fromObject(list).toString();
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	
	
	@Path("/queryinfo")
	@POST
	public String queryinfo(String sql) {
		String result = "";
		System.out.println("SQL: " + sql);
		try {
			String[][] str = DBTools.executeQueryWithTableHead(sql);
			List list = DBTools.arrayToHashtable(str);
			result = JSONArray.fromObject(list).toString();
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
			return result;
		}
	}

	private Hashtable convert(String data) {
		data = CharacterSetHelper.restDecode(data);
		JSONObject obj = JSONObject.fromObject(data);
		Hashtable result = jsonToHash(obj);
		return result;
	}

	private JSONArray convertToList(String data) {
		System.out.println(data);

		System.out.println(data);
		JSONArray array = JSONArray.fromObject(data);
		System.out.println(array);
		return array;
	}

	private Hashtable jsonToHash(JSONObject obj) {
		Hashtable result = new Hashtable();
		Iterator iter = obj.keySet().iterator();
		while (iter.hasNext()) {
			String key = iter.next().toString();
			String value = obj.getString(key);
			result.put(key, value);
		}
		return result;
	}

	private String getQuerySQL(String xpath, String search) {
		String sql = "";
		String orderby = "";
		if (xpath.indexOf("[") != -1) {
			String tablename = xpath.substring(0, xpath.indexOf("["));
			String condition = " where "
					+ xpath.substring(xpath.indexOf("[") + 1,
							xpath.indexOf("]"));

			if (condition.equals(" where ")) {
				condition = "";
			}
			orderby = xpath.substring(xpath.indexOf("]") + 1, xpath.length());
			sql = sql + tablename + condition.toLowerCase();
		} else {
			sql = sql + xpath;
		}
		if ((search != null) && (!search.equals(""))) {
			if (sql.indexOf("where") != -1)
				sql = sql + " and " + search;
			else {
				sql = sql + " where " + search;
			}
		}
		if ((!orderby.equals("")) && (sql.indexOf("count") == -1)) {
			sql = sql + " " + orderby;
		}
		return sql;
	}

	private String getSqlServerLimit(int start, int count, String table) {
		String order = "";
		if (table.indexOf("order") != -1) {
			String[] str = table.split("order");
			table = str[0];
			order = " order " + str[1];
		}
		String result = "";
		int M = start + count;

		result = " select * from ( select row_number()over(" + order
				+ ") row,* from " + table + ") t where t.row between "
				+ (start + 1) + " and " + M;

		return result;
	}

	public User getLoginUser(HttpServletRequest request) {
		User user = null;
		try {
			user = (User) request.getSession().getAttribute("loginUser");
			user = (User) EntityManager.getInstance().getUserForLoginName(
					"system");
			System.out.println("用户类型： " + user.getRolesStr());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	@Path("/judgeusertype")
	@GET
	public String getUserType(@QueryParam("inputname") String inputName,
			@QueryParam("password") String pwd,
			@QueryParam("usertype") String userType) {
		String result = "";
		try {
			User user = EntityManager.getInstance().getUser(inputName, pwd,
					false);
			if (!userType.equals("")) {
				String userT = user.getRolesStr();
				if (userT.indexOf(",") != -1) {
					String[] str = userT.split(",");
					for (int i = 0; i < str.length; i++) {
						String uType = str[i];
						if (uType.equals(userType)) {
							result = "{return:true,result:"
									+ JSONObject.fromObject(user
											.getAttributes()) + "}";
							break;
						}
					}
				} else if (userT.equals(userType)) {
					result = "{return:true,result:"
							+ JSONObject.fromObject(user.getAttributes()) + "}";
				} else {
					result = "{return:您没有权限这样操作！}";
				}
			} else if (user != null) {
				result = "{return:true,result:"
						+ JSONObject.fromObject(user.getAttributes()) + "}";
			}
		} catch (Exception ee) {
			result = ee.getMessage();
			if (result == null)
				result = "{return:用户名或者密码不正确！}";
		} finally {
			return result;
		}
	}
}